<template>
    <div class="work-order-container">
        <!-- 顶部信息栏 -->
        <div class="header-info">
            <div>
                创建人：赵五六
                创建时间：2035-05-11 12:13:28
                最后修改人：赵五六
                修改时间：2022-06-07 19:49:12
            </div>
            <div class="action-buttons">
                <button class="print-btn" @click="handlePrint">打印</button> <!-- 添加打印事件 -->
                <button class="complete-btn">完成</button>
                <button class="close-btn">关闭</button>
            </div>
        </div>

        <!-- 标签栏 -->
        <div class="tab-bar">
            <div class="tab-item" @click="getNamseOfDeclaration()">工单信息</div>
            <div class="tab-item active">报工记录</div>
            <div class="tab-item" @click="FooksHow()">操作记录</div>
        </div>

        <!-- 表格内容 -->
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>工序编码</th>
                        <th>工序名称</th>
                        <th>加工顺序</th>
                        <th>工艺流程</th>
                        <th>负责人</th>
                        <th>所在部门</th>
                        <th>报工时间</th>
                        <th>质检时间</th>
                        <th>完工数量</th>
                        <th>合格数量</th>
                        <th>不良数量</th>
                        <th>工序名称</th>
                        <th>合格率</th>
                        <th>生产人员</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(item, index) in reportRecords" :key="index"
                        :class="{ 'highlight-row': index % 2 === 0 }">
                        <td>{{ index + 1 }}</td>
                        <td>{{ item.workOrderId }}</td>
                        <td>{{ item.workOrderName }}</td>
                        <td>{{ item.workOrderJName }}</td>
                        <td>{{ item.workOrderLName }}</td>
                        <td>{{ item.workOrderFName }}</td>
                        <td>{{ item.workOrderSZName }}</td>
                        <td>{{ item.workOrderBName }}</td>
                        <td>{{ item.workOrderZName || '-' }}</td>
                        <td>{{ item.workOrderWName }}</td>
                        <td>{{ item.workOrderHName || '-' }}</td>
                        <td>{{ item.workOrderBuName || '-' }}</td>
                        <td>{{ item.workOrderGName }}</td>
                        <td>{{ item.workOrderKoo || '0%' }}</td>
                        <td>{{ item.workOrderRName }}</td>
                        <td>{{ item.workOrderState }}</td>
                        <td>
                            <button v-if="item.workOrderState === '未质检'" class="quality-btn"
                                @click="handleQualityCheck(item)">质检</button>
                            <button v-else class="delete-btn">删除</button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 附件区域 -->
        <div class="attachment-section">
            <div v-for="(file, index) in attachments" :key="index" class="file-card">
                <div>{{ file.name }}</div>
                <div>文件大小：{{ file.size }}</div>
                <div>上传日期：{{ file.uploadDate }}</div>
                <div class="file-actions">
                    <button class="view-btn">查看</button>
                    <button class="download-btn">下载</button>
                </div>
            </div>
        </div>

        <!-- 质检弹窗 -->
        <div v-show="isQualityDialogVisible" class="quality-dialog">
            <div class="dialog-content">
                <h3>质检</h3>
                <form @submit.prevent="handleConfirm">
                    <div class="form-group">
                        <label>工序编号：</label>
                        <span>{{ currentQualityItem?.workOrderId || '' }}</span>
                    </div>
                    <div class="form-group">
                        <label>工序名称：</label>
                        <span>{{ currentQualityItem?.workOrderName || '' }}</span>
                    </div>
                    <div class="form-group">
                        <label>负责人：</label>
                        <span>{{ currentQualityItem?.workOrderFName || '' }}</span>
                    </div>
                    <div class="form-group">
                        <label>所在部门：</label>
                        <span>{{ currentQualityItem?.workOrderSZName || '' }}</span>
                    </div>
                    <div class="form-group">
                        <label>生产人员：</label>
                        <span>{{ currentQualityItem?.workOrderRName || '' }}</span>
                    </div>
                    <div class="form-group">
                        <label>完工数量：</label>
                        <span>{{ currentQualityItem?.workOrderWName || 0 }}</span>
                    </div>
                    <div class="form-group">
                        <label>*合格数量：</label>
                        <input type="number" v-model.number="qualifiedCount" :max="currentQualityItem?.workOrderHName"
                            required>
                    </div>
                    <div class="form-group">
                        <label>*不良数量：</label>
                        <input type="number" v-model.number="unqualifiedCount"
                            :max="currentQualityItem?.workOrderBuName" required>
                    </div>
                    <div class="button-group">
                        <button type="button" @click="isQualityDialogVisible = false">取消</button>
                        <button type="submit" class="confirm-btn" @click="wangView()">确定</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>

<script setup>
import axios from 'axios';
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();

// 质检弹窗控制
const isQualityDialogVisible = ref(false);
const currentQualityItem = ref(null);
const qualifiedCount = ref(0);
const unqualifiedCount = ref(0);

// 处理质检按钮点击
const handleQualityCheck = (item) => {
    currentQualityItem.value = item; // 先设置当前质检项
    isQualityDialogVisible.value = true;
    axios.get(`https://localhost:7006/api/Process/WorkOrderFileQuser?WorkOrderId=${item.workOrderId}`).then((res) => {
        currentQualityItem.value = res.data.data[0]
    })
};

// 提交质检结果
const handleConfirm = () => {
    const total = qualifiedCount.value + unqualifiedCount.value;
    const completed = currentQualityItem.value?.completedQuantity;

    if (total > completed) {
        alert("合格数量与不良数量之和不能超过完工数量！");
        return;
    }

    // 更新数据
    const index = reportRecords.value.findIndex(
        item => item.workOrderId === currentQualityItem.value.workOrderId
    );

    if (index !== -1) {
        reportRecords.value[index] = {
            ...reportRecords.value[index],
            status: '已质检',
            qualifiedCount: qualifiedCount.value,
            unqualifiedCount: unqualifiedCount.value,
            inspectionTime: new Date().toLocaleString()
        };
    }

    isQualityDialogVisible.value = false;
};

// 模拟数据
const reportRecords = ref([]);

// 附件数据
const attachments = ref([
    {
        name: '工艺图纸.pdf',
        size: '2.4MB',
        uploadDate: '2023-03-14 10:00'
    },
    {
        name: '质检标准.doc',
        size: '1.2MB',
        uploadDate: '2023-03-14 11:30'
    }
]);

const Foow = () => {
    axios.get("https://localhost:7006/api/Process/WorkOrderQuser").then((res) => {
        reportRecords.value = res.data.data
    })
}

const wangView = () => {
    if (currentQualityItem.value.workOrderState == "未质检") {
        currentQualityItem.value.workOrderState = "已质检"
    }
    const fromw = {
        workOrderId: currentQualityItem.value.workOrderId, // 工序编码（取自当前项）
        workOrderName: currentQualityItem.value.workOrderName, // 工序名称（取自当前项）
        workOrderJName: currentQualityItem.value.workOrderJName, // 加工顺序（取自当前项）
        workOrderLName: currentQualityItem.value.workOrderLName, // 工艺流程（取自当前项）
        workOrderFName: currentQualityItem.value.workOrderFName, // 负责人（取自当前项）
        workOrderSZName: currentQualityItem.value.workOrderSZName, // 所在部门（取自当前项）
        workOrderBName: currentQualityItem.value.workOrderBName, // 报工时间（取自当前项）
        workOrderZName: new Date().toLocaleString(), // 质检时间（当前时间）
        workOrderWName: currentQualityItem.value.workOrderWName, // 完工数量（取自当前项）
        workOrderHName: qualifiedCount.value.toString(), // 合格数量（表单输入）
        workOrderBuName: unqualifiedCount.value.toString(), // 不良数量（表单输入）
        workOrderGName: currentQualityItem.value.workOrderGName, // 工序名称（重复字段，需确认是否保留）
        workOrderKoo: `${(qualifiedCount.value / currentQualityItem.value.workOrderWName * 100).toFixed(2)}%`, // 计算合格率
        workOrderRName: currentQualityItem.value.workOrderRName, // 生产人员（取自当前项）
        workOrderState: currentQualityItem.value.workOrderState // 状态（更新后的值）

    };
    console.log(fromw);
    axios.put("https://localhost:7207/api/Production/WorkOrderUpdate", fromw).then((res) => {
        if (res.data.code == 212) {
            ElMessage({
                message: '修改成功',
                type: 'success',
            })
            isQualityDialogVisible.value = false;
            Foow();
        } else {
            ElMessage.error('修改失败')
        }
    })
}

const getNamseOfDeclaration = () => {
    router.push("/NewproductionworkorderShowView")
}

const FooksHow = () => {
    router.push("/WorkOrderDetailsPageOperatio")
}

// 新增打印功能
const handlePrint = () => {
    window.print(); // 调用浏览器原生打印功能
};

onMounted(() => {
    Foow()
})

</script>

<style scoped>
.work-order-container {
    padding: 20px;
    font-family: Arial, sans-serif;
}

.header-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 10px;
    background: #f5f5f5;
    border-radius: 4px;
}

.action-buttons button {
    margin-left: 10px;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.print-btn {
    background: #e0e0e0;
}

.complete-btn {
    background: #67c23a;
    color: white;
}

.close-btn {
    background: #f56c6c;
    color: white;
}

.tab-bar {
    margin: 20px 0;
    border-bottom: 1px solid #ddd;
}

.tab-item {
    display: inline-block;
    padding: 12px 24px;
    margin-right: 5px;
    cursor: pointer;
    border: 1px solid transparent;
}

.tab-item.active {
    border-color: #ddd;
    border-bottom-color: white;
    border-radius: 4px 4px 0 0;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin: 20px 0;
}

th,
td {
    border: 1px solid #ebeef5;
    padding: 12px;
    text-align: left;
}

.highlight-row {
    background-color: #fafafa;
}

.quality-btn {
    background: #409eff;
    color: white;
    padding: 6px 12px;
    border: none;
    border-radius: 4px;
}

.delete-btn {
    background: #f56c6c;
    color: white;
    padding: 6px 12px;
    border: none;
    border-radius: 4px;
}

.attachment-section {
    display: flex;
    gap: 20px;
    margin-top: 30px;
}

.file-card {
    border: 1px solid #ebeef5;
    padding: 15px;
    border-radius: 4px;
    width: 220px;
}

.file-actions {
    margin-top: 10px;
}

.file-actions button {
    margin-right: 10px;
    padding: 6px 12px;
    background: #f5f5f5;
    border: none;
    border-radius: 4px;
}

.quality-dialog {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
}

.dialog-content {
    background: white;
    padding: 20px;
    border-radius: 8px;
    width: 500px;
}

.form-group {
    margin: 15px 0;
    display: flex;
    align-items: center;
}

.form-group label {
    width: 100px;
    text-align: right;
    margin-right: 15px;
}

.form-group span {
    flex: 1;
    padding: 8px;
    background: #f5f5f5;
    border-radius: 4px;
}

.form-group input {
    flex: 1;
    padding: 8px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
}

.button-group {
    text-align: right;
    margin-top: 20px;
}

.button-group button {
    margin-left: 10px;
    padding: 8px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.confirm-btn {
    background: #409eff;
    color: white;
}

/* 新增打印样式（注意scoped穿透） */
@media print {

    ::v-deep .action-buttons,
    /* 隐藏操作按钮 */
    ::v-deep .tab-bar,
    /* 隐藏标签栏 */
    ::v-deep .quality-dialog {
        /* 隐藏质检弹窗 */
        display: none !important;
    }

    ::v-deep .work-order-container {
        padding: 10px;
        /* 减少打印边距 */
    }

    ::v-deep table {
        border-collapse: collapse;
        width: 100%;
    }

    ::v-deep th,
    ::v-deep td {
        border: 1px solid #000;
        /* 增强表格边框 */
        page-break-inside: avoid;
        /* 避免表格跨页断裂 */
    }
}
</style>